package com.xuecheng.rabbitmq.header;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.Hashtable;
import java.util.Map;
import java.util.concurrent.TimeoutException;

public class HeaderConsumer {
    private static final String QUEUE_INFORM_EMAIL = "queue_inform_email";
    private static final String QUEUE_INFORM_SMS = "queue_inform_sms";
    //不处理路由键交换机名称
    private static final String EXCHANGE_FANOUT_INFORM = "exchange_header_inform";

    public static void main(String[] args) throws IOException, TimeoutException {
        //创建连接
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("47.99.79.246");
        factory.setPort(5672);
        factory.setUsername("admin");
        factory.setPassword("admin");
        factory.setVirtualHost("/");
        //创建tpc连接
        Connection connection = factory.newConnection();
        //创建交换机通道
        Channel channel = connection.createChannel();
        //声明交换机
        channel.exchangeDeclare(EXCHANGE_FANOUT_INFORM, BuiltinExchangeType.HEADERS);


        //声明队列
        channel.queueDeclare(QUEUE_INFORM_EMAIL, true,false, false,null);
        channel.queueDeclare(QUEUE_INFORM_SMS, true,false, false,null);

        //绑定队列
        Map<String,Object> h_e = new Hashtable<>();
        h_e.put("inform_type","email");
        Map<String,Object> h_s = new Hashtable<>();
        h_s.put("inform_type","email");
        channel.queueBind(QUEUE_INFORM_SMS,EXCHANGE_FANOUT_INFORM,"",h_s);
        channel.queueBind(QUEUE_INFORM_EMAIL,EXCHANGE_FANOUT_INFORM,"",h_e);

     DefaultConsumer defaultConsumer = new DefaultConsumer(channel){
         @Override
         public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
             //交换机
             String exchange = envelope.getExchange();
             //路由
             String routingKey = envelope.getRoutingKey();
             //消息id
             long deliveryTag = envelope.getDeliveryTag();
             //消息内容
             String msg = new String(body,"utf-8");
             System.out.println("header接收的消息: "+msg);
         }
     };
     channel.basicConsume(QUEUE_INFORM_EMAIL,true,defaultConsumer);
    }
}
